﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SpaceSquirrel.Automation
{
	public class AcornTopAutomation : SpriteAutomation
	{
		private static readonly double[][] TRAIL;

		static AcornTopAutomation()
		{
			double ACORN_TOP_SPEED = 4.5;
			List<double[]> trail = new List<double[]>();
			double[] ball = new double[] { 0, 0 };
			double[][] waypoints = new double[][] {
				new double[] { -1, 0 },
				new double[] { -6, 0 },
				new double[] { -6.6, -0.4 },
				new double[] { -7, -1 },
				new double[] { -6.6, -1.6 },
				new double[] { -6, -2 },
				new double[] { -1, -2 },
				new double[] { -0.4, -1.6 },
				new double[] { 0, -1 },
				new double[] { 0, -.5 }
			};

			double v = ACORN_TOP_SPEED;

			for (int i = 0; i < waypoints.Length; ++i)
			{
				double[] target = waypoints[i];
				double tx = target[0] * 16;
				double ty = target[1] * 16;

				bool done = false;
				while (!done)
				{
					double dx = tx - ball[0];
					double dy = ty - ball[1];
					double distance = Math.Sqrt(dx * dx + dy * dy);
					if (distance <= v)
					{
						done = true;
						trail.Add(new double[] { tx, ty });
						ball[0] = tx;
						ball[1] = ty;
					}
					else
					{
						dx *= v / distance;
						dy *= v / distance;
						ball[0] += dx;
						ball[1] += dy;
						trail.Add(new double[] { 
							(int)(10 * ball[0]) / 10.0,
							(int)(10 * ball[1]) / 10.0
						});
					}
				}
			}

			TRAIL = trail.ToArray();
		}

		private int trailIndex;
		private double startX;
		private double startY;
		public bool completed;
		private int xSign;
		private int ySign;
		private bool goLeft;
		public Sprite body;
		
		public AcornTopAutomation(Sprite sprite)
			: base(sprite)
		{
			this.trailIndex = 0;
			this.startX = sprite.modelX;
			this.startY = sprite.modelY;
			this.completed = false;
		}

		public void setGoLeft(bool goLeft)
		{
			this.goLeft = goLeft;
			this.xSign = goLeft ? 1 : -1;
		}

		public void setGoUp(bool goUp)
		{
			this.ySign = goUp ? 1 : -1;
		}

		public override void DoStuff(PlayScene scene)
		{
			if (this.trailIndex < TRAIL.Length)
			{
				double rawX = TRAIL[this.trailIndex][0];
				double rawY = TRAIL[this.trailIndex][1];

				rawX *= this.xSign;
				rawY *= this.ySign;

				double targetX = this.startX + rawX;
				double targetY = this.startY + rawY;

				double dx = targetX - this.sprite.modelX;
				double dy = targetY - this.sprite.modelY;

				this.sprite.dx = dx;
				this.sprite.dy = dy;

				++this.trailIndex;
			}
			else
			{
				if (this.completed)
				{
					this.sprite.dead = true;
				}
				this.completed = true;
			}
		}
	}
}
